package com.fengye.middleware.rabbitmq.boot.demo.object;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 *
 * @author sky
 * @date 2021年06月09日 11:16 上午
 */
@Component
@Slf4j
public class ObjectPublisher {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.object.info.exchange.name:object_change_name}")
    private String objectExchangeName;

    @Value("${mq.object.info.routing.key.name:object_routing_key_name}")
    private String objectRoutingKeyName;


    public void sendObjectMsg(Person person) {
        if (person != null) {
            try {
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                rabbitTemplate.setExchange(objectExchangeName);
                rabbitTemplate.setRoutingKey(objectRoutingKeyName);

                rabbitTemplate.convertAndSend(person, new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        MessageProperties messageProperties = message.getMessageProperties();
                        // 设置消息的持久化模式
                        messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);

                        messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, Person.class);

                        return message;
                    }
                });

                log.info("基本消息模型：生产者-发送对象类型的消息：{}", person);
            } catch (Exception e) {
                log.error("基本消息模型：生产者-发送消息异常：{}", person, e.fillInStackTrace());
            }
        }
    }
}
